package models

import (
	"awesome-devops/boot"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	"strings"
)

type ProcessFiles struct {
	BaseModel
	Id           uint   `json:"id"`
	ProjectId    int    `json:"project_id"`
	ProcessId    int    `json:"process_id"`
	UniqueId     string `json:"unique_id"`
	TemplateArgs string `json:"template_args"`
	Content      string `json:"content"`
	Path         string `json:"path"`
	CreateTime   string `json:"create_time"`
	UpdateTime   string `json:"update_time"`
	DeleteTime   int    `json:"delete_time"`
}

func (baseModel *ProcessFiles) TableName() string {
	return "ops_files"
}

func (baseModel *ProcessFiles) GetFilesByProcessId(processIds []int) map[int][]ProcessFiles {
	processFiles := ProcessFiles{}
	var processFilesList []ProcessFiles
	boot.GetDbConnection().Table(processFiles.TableName()).
		Where("process_id in ?", processIds).
		Where("delete_time=0").
		Find(&processFilesList)
	res := map[int][]ProcessFiles{}
	for _, item := range processFilesList {
		if _, ok := res[item.ProcessId]; !ok {
			res[item.ProcessId] = make([]ProcessFiles, 0)
		}
		res[item.ProjectId] = append(res[item.ProjectId], item)
	}
	return res
}

func (baseModel *ProcessFiles) GetRunFile(sysArgs map[string]string, runningArgs map[string]string) (runShell string, err error) {
	args := make(map[string]string)
	argsData, err := commonhelper.JsonDecodeWithErr(baseModel.TemplateArgs)
	if err == nil {
		args = argsData.(map[string]string)
	}
	template := baseModel.Content
	template = baseModel.format(template, sysArgs)
	template = baseModel.format(template, args)
	template = baseModel.format(template, runningArgs)
	template = strings.Replace(template, "\r", "", -1)
	return template, nil
}

func (baseModel *ProcessFiles) format(shell string, sysArgs map[string]string) (runShell string) {
	for key, value := range sysArgs {
		shell = strings.ReplaceAll(shell, "{{"+key+"}}", value)
	}
	return shell
}

func (baseModel *ProcessFiles) WriteRunFile(absPath string, sysArgs map[string]string, runningArgs map[string]string) {
	template, _ := baseModel.GetRunFile(sysArgs, runningArgs)
	commonhelper.WriteFile(absPath+"/"+baseModel.Path, template, 0777)
}

func WriteOpsFiles(files []ProcessFiles, absPath string, sysArgs map[string]string, runningArgs map[string]string) {
	for _, file := range files {
		file.WriteRunFile(absPath, sysArgs, runningArgs)
	}
}
